package com.whu.MenuHub.security;


import com.whu.MenuHub.service.Impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DbUserDetailService implements UserDetailsService {

    @Autowired
    UserServiceImpl userService;

    @Value("${Customer.Authority}")
    public String customerAuthortiStr;
    @Value("${owner.Authority}")
    public String ownerAuthortiStr;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.whu.MenuHub.domain.User user = userService.getUserByUserName(username);
        if (user == null) {
            System.out.println("找不到"+username);
            //throw new UsernameNotFoundException("用户：" + username + " 未注册");
            return null;
        }
        return User.builder()
                .username(username)
                .password(user.getPassword())
                .authorities(getAuthorities(user))
                .build();
    }

    public GrantedAuthority[] getAuthorities(com.whu.MenuHub.domain.User user) {
        //查看用户有哪些权限
        List<GrantedAuthority> authorities = new ArrayList<>();
        //将角色对应的权限用逗号分割，并获得一个权限数组
        String[] authorityStrs;

        //商家的权限
        if(user.getRole().equals("owner")){
            authorityStrs=ownerAuthortiStr.split(",");
        }
        else{
             //顾客的权限
             authorityStrs = customerAuthortiStr.split(",");
        }
        for (String auth : authorityStrs) {
            authorities.add(new SimpleGrantedAuthority(auth));
            }
        //只可以删除/修改自己的信息，增加这个作为权限判断
        authorities.add(new SimpleGrantedAuthority(user.getId().toString()));
        authorities.add(new SimpleGrantedAuthority(user.getUsername()));
        //把用户的身份信息也放在token中
        authorities.add(new SimpleGrantedAuthority(user.getRole()));
        return authorities.toArray(new GrantedAuthority[authorities.size()]);
    }

}
